part of 'utils.dart';

final colorRegExp = RegExp(r"^#([a-zA-Z0-9]{3}|[a-zA-Z0-9]{6})$");

Color? getColor(dynamic value) {
  if (value == null) return null;
  if (value is Color) return value;
  if (value is VanBgColor) return value.color;
  if (value is Gradient) return value.colors.firstOrNull;
  if (value is int) return Color(value);
  if (value is String && colorRegExp.hasMatch(value)) {
    if (value.length == 4) {
      int r = int.parse(value.substring(1, 2) + value.substring(1, 2), radix: 16);
      int g = int.parse(value.substring(2, 3) + value.substring(2, 3), radix: 16);
      int b = int.parse(value.substring(3, 4) + value.substring(3, 4), radix: 16);
      return Color.fromRGBO(r, g, b, 1);
    } else if (value.length == 7) {
      int r = int.parse(value.substring(1, 3), radix: 16);
      int g = int.parse(value.substring(3, 5), radix: 16);
      int b = int.parse(value.substring(5, 7), radix: 16);
      return Color.fromRGBO(r, g, b, 1);
    }
  }
  return null;
}

Gradient? getGradient(dynamic value) {
  if (value == null) return null;
  if (value is Gradient) return value;
  return null;
}

VanBgColor? getBackground(dynamic value) => VanBgColor(value);

String? getString(value) {
  if (value == null) return null;
  if (value is String) return value;
  return null;
}

int? getInt(value) {
  if (value == null) return null;
  if (value is int) return value;
  if (value is double) return int.parse(value.toString());
  if (value is String) return int.parse(value);
  return null;
}

double? getDouble(value) {
  if (value == null) return null;
  if (value is double) return value;
  if (value is int) return value.toDouble();
  if (value is String) return double.tryParse(value);
  if (value is EdgeInsets) return value.left;
  if (value is BorderRadius) return value.topLeft.x;
  return null;
}

getBorderRadius(value) {
  if (value == null) return null;
  if (value is BorderRadius) return value;
  double? val = getDouble(value);
  if (val != null) return BorderRadius.all(Radius.circular(val));
  return null;
}

EdgeInsets? getEdgeInsets(value) {
  if (value == null) return null;
  if (value is EdgeInsets) return value;
  double? val;
  if (value is int) val = value.toDouble();
  if (value is double) val = value;
  if (value is String) val = double.tryParse(value);
  if (val != null) return EdgeInsets.all(val);
  return null;
}

double? calcLineHeight({double? lineHeight, double? fontSize}) {
  if (lineHeight == null || fontSize == null || fontSize <= 0 || lineHeight <= 6) return lineHeight;
  return lineHeight / fontSize;
}
double? calcHeight({double? lineHeight, double fontSize = 0}) {
  if (lineHeight == null || fontSize <= 0 || lineHeight > 6) return lineHeight;
  return lineHeight * fontSize;
}


